var loginIdKey = "loginId";
var encryptedPasswordKey = "encryptedPassword";

/*-------- Log in */

function loginCallback(data, status, request) {

	/* Was the login request successful? If not, show the error and stay */

	var status = $(data).find("Responses > Login > Status").text();

	if (status == "Failed") {
		$("#loginError").html("Incorrect credentials; please try again.");
		$("#loginId").focus();
	} else {

		var encryptedPassword = $(data).find("Responses > Login > EncryptedPassword").text();
		var loginId = $(data).find("Responses > Login > LoginId").text();

		/* If we have returned an encrypted password, the user wants remembered */
		if (encryptedPassword != "") {
			localStorage.setItem(loginIdKey, loginId);
			localStorage.setItem(encryptedPasswordKey, encryptedPassword);
		}

		boardDisplay(data);

		$("#loginError").html("");
		displayUserInfo(data);
	}

}

/* Make a server request to perform the login and get boards and user data back. */

function loginRequest(loginId, password, returnEncryptedPassword) {

	var xml = "<Requests>" + loginMessage(loginId, password, false, returnEncryptedPassword);
	xml += boardsMessage() + userInfoMessage() + "</Requests>";

	sendMessage(xml, loginCallback);
}

function loginButtonClicked() {

	var loginId = $("#loginId").val();
	var password = $("#password").val();
	var rememberMe = $("#rememberMeCheckBox").is(":checked");

	loginRequest(loginId, password, rememberMe);

	$("#loginId").val("");
	$("#password").val("");
}

/*-------- Log out */

function logoutCallback(data, status, request) {

	boardDisplay(data);

	var response = $(data).find("Logout").text();

	if (response == "Success") {
		$("#loggedInSection").slideUp();
		$("#loginSection").slideDown();
	}

	$("#loginId").focus();
}

/* Send a logout request and a boards request, as you may have access to fewer boards logged out */

function logoutButtonClicked() {

	var xml = "<Requests>" + logoutMessage() + boardsMessage() + "</Requests>";
	sendMessage(xml, logoutCallback);

}
